package cn.sumpu.app.coolsk.biz.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

//import org.springframework.transaction.annotation.Transactional;

import cn.sumpu.app.coolsk.biz.ProductBiz;
import cn.sumpu.app.coolsk.constant.Table;
import cn.sumpu.app.coolsk.dao.ProductDao;
import cn.sumpu.app.coolsk.domain.Product;
import cn.sumpu.app.coolsk.domain.ProductPrice;
import cn.sumpu.app.coolsk.exception.AppBusinessException;
import cn.sumpu.toolkit.common.page.PageModel;
import cn.sumpu.toolkit.common.util.Common;
import cn.sumpu.toolkit.common.util.Encode;

public class ProductBizImpl implements ProductBiz {
    private Calendar                     cal = Calendar.getInstance();
    private ProductDao                   productDao;

    private DataSourceTransactionManager transactionManager;
    @Autowired
    private IdentifierBizImpl            identifierBiz;

    public void setProductDao(ProductDao productDao) {
        this.productDao = productDao;
    }

    public void setTransactionManager(DataSourceTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public PageModel getProductList(Integer page, Integer pagesize, String name, String type, String company) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        page=page==null?1:page;
        int size = pagesize;
        map.put("startId", (page - 1) * size);
        map.put("pageSize", size);
        if (!Common.empty(type)) {
            map.put("type", type);
        }
        if (!Common.empty(name)) {
            map.put("name", "%" + name + "%");
        }
        if (!Common.empty(company)) {
            map.put("company", company);
        }
        int count = productDao.getProductCount(map);
        PageModel pm = new PageModel();
        pm.setCurrentPage(page);
        pm.setList(productDao.getProduct(map));
        pm.setPageSize(size);
        pm.setTotalRecord(count);
        pm.setTotalPage((count + size - 1) / size);
        return pm;
    }

    @Override
    public Product saveProduct(Product product) throws AppBusinessException {
        if (product != null) {
            if (Common.empty(product.getId())) {
                product.setId(identifierBiz.generateId(Table.PRODUCT));
                productDao.insertProduct(product);
            } else {
                productDao.updateProduct(product);
            }
        }
        return product;
    }

    @Override
    public Product getProductById(String id) throws AppBusinessException {
        if (Common.empty(id))
            return null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        List<Product> plist = productDao.getProduct(map);
        if (plist != null && plist.size() > 0) {
            return plist.get(0);
        }
        return null;
    }

    @Override
    public Product delProduct(String id) throws AppBusinessException {
        Product product = getProductById(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        productDao.delProduct(map);
        return product;
    }

    @Override
    public ProductPrice getTodayPrice(Product product) throws AppBusinessException {
        if (product == null)
            return null;
        ProductPrice dayPrice = new ProductPrice();
        int befores = product.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        String now = Common.getFormatDate(startDate, "yyyy-MM-dd");
        dayPrice.setPriceA(product.getPriceMin());
        dayPrice.setSpDate(now);
        List<ProductPrice> tpList = getProductPrice(product.getId());
        if (tpList != null && tpList.size() > 0) {
            for (ProductPrice productPrice : tpList) {
                String spDate = productPrice.getSpDate();
                if (now.equals(spDate)) {
                    dayPrice = productPrice;
                    break;
                }
            }
        }
        return getDayPrice(product, null);
    }

    @Override
    public List<ProductPrice> resPriceList(Product product) throws AppBusinessException {
        if (product == null)
            return null;
        List<ProductPrice> resPriceList = new ArrayList<ProductPrice>();

        List<ProductPrice> tpList = getProductPrice(product.getId());
        int befores = product.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        cal.setTime(startDate);
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < weekday - 1; i++) {
            Date prevDate = Common.addDate(startDate, -weekday + i + 1);
            ProductPrice tp = new ProductPrice();
            tp.setPriceComHas(product.getPriceComHas());
            tp.setSpDate(Common.getFormatDate(prevDate, "yyyy-MM-dd"));
            resPriceList.add(tp);
        }

        for (int i = 0; i < 43 - weekday; i++) {
            ProductPrice tp = new ProductPrice();
            Date spDate = Common.addDate(startDate, i);
            String tmpDate = Common.getFormatDate(spDate, "yyyy-MM-dd");
            tp.setSpDate(tmpDate);
            tp.setPriceA(product.getPriceMin());
            tp.setPriceComHas(product.getPriceComHas());
            for (ProductPrice productPrice : tpList) {
                String spDate1 = productPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = productPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        cal.add(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        weekday = cal.get(Calendar.DAY_OF_WEEK);
        for (int i = 0; i < weekday - 1; i++) {
            Date prevDate = Common.addDate(cal.getTime(), -weekday + i + 1);
            String tmpDate = Common.getFormatDate(prevDate, "yyyy-MM-dd");
            ProductPrice tp = new ProductPrice();
            tp.setPriceA(product.getPriceMin());
            tp.setSpDate(tmpDate);
            tp.setPriceComHas(product.getPriceComHas());
            for (ProductPrice productPrice : tpList) {
                String spDate1 = productPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = productPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        for (int i = 0; i < 43 - weekday; i++) {
            ProductPrice tp = new ProductPrice();
            Date spDate = Common.addDate(cal.getTime(), i);
            String tmpDate = Common.getFormatDate(spDate, "yyyy-MM-dd");
            tp.setSpDate(tmpDate);
            tp.setPriceA(product.getPriceMin());
            tp.setPriceComHas(product.getPriceComHas());
            for (ProductPrice productPrice : tpList) {
                String spDate1 = productPrice.getSpDate();
                if (tmpDate.equals(spDate1)) {
                    tp = productPrice;
                    tp.setPriceComHas(true);
                    break;
                }
            }
            resPriceList.add(tp);
        }

        return resPriceList;
    }

    @Override
    public ProductPrice getDayPrice(Product product, String date) throws AppBusinessException {
        if (product == null)
            return null;
        String now = null;
        ProductPrice dayPrice = new ProductPrice();
        int befores = product.getBefores();
        Date startDate = Common.addDate(new Date(), befores + 1);
        if (Common.empty(date)) {
            now = Common.getFormatDate(startDate, "yyyy-MM-dd");
        } else {
            now = date;
        }
        dayPrice.setPriceA(product.getPriceMin());
        dayPrice.setSpDate(now);

        List<ProductPrice> tpList = getProductPrice(product.getId());
        if (tpList != null && tpList.size() > 0) {
            for (ProductPrice productPrice : tpList) {
                String spDate = productPrice.getSpDate();
                if (now.equals(spDate)) {
                    dayPrice = productPrice;
                    break;
                }
            }
        }
        return dayPrice;
    }

    @Override
    public List<ProductPrice> getProductPrice(String productId) throws AppBusinessException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("productId", productId);
        return productDao.getProductPrice(map);
    }

    @Override
    public void saveProductPrice(String productId, String tpList) throws AppBusinessException {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();// 事务定义类
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);// 设置事务传播属性
        TransactionStatus status = transactionManager.getTransaction(def);// 返回事务对象
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("productId", productId);
            productDao.delProductPrice(map);

            JSONArray list = JSONArray.fromObject(Encode.unescape(tpList));
            for (Object object : list) {
                ProductPrice tp = (ProductPrice) JSONObject.toBean((JSONObject) object, ProductPrice.class);
                productDao.insertProductPrice(tp);
            }
            transactionManager.commit(status);// 提交事务
        } catch (Exception e) {
            transactionManager.rollback(status);// 回滚事务
            throw new AppBusinessException(e);
        }

    }

}
